'use client';

import { useEffect, useState } from 'react';
import { createPortal } from 'react-dom';
import { useMultiChainWallet } from '@/contexts/MultiChainWalletContext';

interface ExtendedMultiChainContext {
  connected: boolean;
  address: string | null;
  connectWallet: (chain: 'bsc' | 'xlayer', provider?: unknown, providerId?: string) => Promise<void>;
  disconnectWallet: () => Promise<void>;
  evmProviderId?: string | null;
}

interface EVMProvider {
  id: string;
  label: string;
  icon: string;
  provider: unknown;
  isDetected?: boolean;
}

interface UnifiedWalletButtonProps {
  chain: 'bsc' | 'xlayer' | 'solana';
  className?: string;
}

export function UnifiedWalletButton({ chain, className = '' }: UnifiedWalletButtonProps) {
  const { connected, address, connectWallet, disconnectWallet, evmProviderId } = useMultiChainWallet() as unknown as ExtendedMultiChainContext;
  const [showModal, setShowModal] = useState(false);
  const [connecting, setConnecting] = useState(false);
  const [providers, setProviders] = useState<EVMProvider[]>([]);

  // 统一展示固定钱包列表（Phantom / MetaMask / OKX / MetaMask 再次）
  useEffect(() => {
    const detect = () => {
  interface AnyEthereumProvider { providers?: unknown[]; [k: string]: unknown }
  const w = window as unknown as { solana?: unknown; ethereum?: AnyEthereumProvider };
      const eth = w.ethereum;
      const sol = w.solana;

      // 收集可能的多 provider
      const rawProviders: unknown[] = [];
      if (eth && Array.isArray(eth.providers)) rawProviders.push(...eth.providers);
      else if (eth) rawProviders.push(eth);

      const findProvider = (predicate: (p: Record<string, unknown>) => boolean): unknown | null => {
        for (const p of rawProviders) { 
          try { if (predicate(p as Record<string, unknown>)) return p; } catch {}
        }
        // 单 provider 情况再检查一次
        if (rawProviders.length === 0 && eth && predicate(eth as Record<string, unknown>)) return eth;
        return null;
      };

      const phantomAvailable = !!sol;
  const hasFlag = (obj: Record<string, unknown>, key: string) => Boolean((obj as { [k: string]: unknown })[key]);
  const metamaskProv = findProvider(p => hasFlag(p, 'isMetaMask'));
  const okxProv = findProvider(p => hasFlag(p, 'isOkxWallet') || hasFlag(p, 'isOKExWallet'));
      const metamaskProv2 = metamaskProv; // 第二个 MetaMask 条目（保持与示例一致）

      const list: EVMProvider[] = [
        {
          id: 'phantom',
          label: 'Phantom',
          icon: '',
          provider: sol || null,
          isDetected: phantomAvailable,
        },
        {
          id: 'metamask',
          label: 'MetaMask',
          icon: '',
          provider: metamaskProv,
          isDetected: !!metamaskProv,
        },
        {
          id: 'okx',
          label: 'OKX Wallet',
          icon: '',
          provider: okxProv,
          isDetected: !!okxProv,
        },
        {
          id: 'metamask-duplicate',
          label: 'MetaMask',
          icon: '',
          provider: metamaskProv2,
          isDetected: !!metamaskProv2,
        },
      ];

      setProviders(list);
    };
    const t = setTimeout(detect, 300);
    return () => clearTimeout(t);
  }, [chain]);

  const handleConnect = async (provider: EVMProvider) => {
    try {
      setConnecting(true);
      console.log(`尝试连接 ${provider.label} 钱包... (id=${provider.id}) 当前主链=${chain}`);
      
      // Phantom -> 走 solana；其他 -> 若当前是 solana 默认用 bsc，否则沿用当前
      const isPhantom = provider.id === 'phantom';
      if (isPhantom) {
        // 这里类型上 connectWallet 只声明了 bsc|xlayer，运行时支持 solana，使用类型断言
        (connectWallet as unknown as (c: 'solana'|'bsc'|'xlayer', p?: unknown, id?: string)=>Promise<void>)('solana');
      } else {
        const targetChain: 'bsc' | 'xlayer' = chain === 'solana' ? 'bsc' : (chain === 'bsc' ? 'bsc' : 'xlayer');
        (connectWallet as unknown as (c: 'solana'|'bsc'|'xlayer', p?: unknown, id?: string)=>Promise<void>)(targetChain, provider.provider, provider.id);
      }
      setShowModal(false);
    } catch (error) {
      console.error(`连接 ${provider.label} 钱包失败:`, error);
      alert(`Failed to connect to ${provider.label}. Please try again.`);
    } finally {
      setConnecting(false);
    }
  };

  const handleDisconnect = async () => {
    await disconnectWallet();
  };

  if (connected && address) {
    return (
      <button
        onClick={handleDisconnect}
        className={`wallet-adapter-button wallet-adapter-button-trigger ${className}`}
        tabIndex={0}
        type="button"
        style={{ pointerEvents: 'auto' }}
      >
  {address.slice(0, 4)}...{address.slice(-4)} {evmProviderId ? `(${evmProviderId})` : ''}
      </button>
    );
  }

  return (
    <>
      <button
        onClick={() => setShowModal(true)}
        className={`wallet-adapter-button wallet-adapter-button-trigger ${className}`}
        tabIndex={0}
        type="button"
        style={{ pointerEvents: 'auto' }}
        disabled={connecting}
      >
        {connecting ? 'Connecting...' : 'Select Wallet'}
      </button>

      {/* 完全模仿 Solana 钱包的弹窗样式 */}
      {showModal && createPortal(
        <div
          className="wallet-adapter-modal-wrapper"
          onClick={(e) => {
            if (e.target === e.currentTarget) setShowModal(false);
          }}
        >
          <div>
            <button
              className="wallet-adapter-modal-button-close"
              onClick={() => setShowModal(false)}
            >
              <svg width="14" height="14">
                <path d="M14 12.461 8.3 6.772l5.234-5.233L12.006 0 6.772 5.234 1.54 0 0 1.539l5.234 5.233L0 12.006l1.539 1.528L6.772 8.3l5.69 5.7L14 12.461z" />
              </svg>
            </button>
            <h1 className="wallet-adapter-modal-title">Connect a wallet on {chain === 'bsc' ? 'BSC' : 'XLayer'} to continue</h1>
            <ul className="wallet-adapter-modal-list">
              {providers.length === 0 ? (
                <li className="wallet-adapter-modal-list-more">
                  <div style={{ textAlign: 'center', padding: '2rem', color: '#666' }}>
                    <p style={{ marginBottom: '0.5rem' }}>No wallet found</p>
                    <p style={{ fontSize: '12px' }}>Please install a supported wallet extension</p>
                  </div>
                </li>
              ) : (
                providers.map((provider) => (
                  <li key={provider.id}>
                    <button
                      className="wallet-adapter-button"
                      onClick={() => handleConnect(provider)}
                      disabled={connecting}
                      tabIndex={0}
                      type="button"
                    >
                      <i className="wallet-adapter-button-start-icon">
                        {/* eslint-disable-next-line @next/next/no-img-element */}
                        <img
                          alt={`${provider.label} icon`}
                          src={provider.icon}
                          style={{ width: '20px', height: '20px' }}
                        />
                      </i>
                      {provider.label}
                      {provider.isDetected && <span>Detected</span>}
                    </button>
                  </li>
                ))
              )}
            </ul>
          </div>
        </div>,
        // createPortal 需要一个非 null 容器；在 SSR 时返回一个占位 <div />
  (typeof document !== 'undefined' ? document.body : { nodeType: 1 } as unknown as HTMLElement)
      )}
    </>
  );
}
